﻿//  

#region

using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.ServiceLocation;

#endregion

namespace pushbomb.composite.core.DynamicObject
{
    /// <summary>
    /// Dynamic Object
    /// </summary>
    [DataContract(IsReference = true)]
    public class DynamicObject : IDynamicObject
    {
        private readonly IExtensionCollection _extensions;
        private readonly IRegionManager _rm;
        private bool _disposed;


        public DynamicObject(IServiceLocator locator, IExtensionCollection extensions)
        {
            _rm = locator.GetInstance<IRegionManager>();
            DynamicProperties = new DynamicProperyBag();
            _extensions = extensions;

            foreach (var w in _extensions)
                w.Attach(this);
        }

        #region IDynamicObject Members

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public IExtensionCollection<DynamicObject> Extensions
        {
            get { return _extensions; }
        }

        public void AddToViewRegion(String name)
        {
            _rm.Regions[name].Add(this);
        }

        [DataMember]
        public DynamicProperyBag DynamicProperties { get; set; }

        #endregion

        ~DynamicObject()

        {
            Dispose(false);
        }


        private void Dispose(bool fromDispose)
        {
            if (!fromDispose) return;
            if (_disposed) return;
            if (_extensions != null)
                DetachAll();

            _disposed = true;
        }

        private void DetachAll()
        {
            foreach (var x in _extensions)
                x.Detach(this);
        }
    }
}